<?php
/**
 * 案由控制器
 */

declare (strict_types = 1);

namespace app\controller\lawcase;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Casecause extends BaseController
{
    /**
     * 获取案由列表
     */
    public function list()
    {
        try {
            $param = Request::param();
            
            // 构建查询条件
            $where = [];
            $where[] = ['delete_time', '=', 0];
            
            // 关键词搜索
            if (!empty($param['keywords'])) {
                $where[] = ['name', 'like', '%' . trim($param['keywords']) . '%'];
            }
            
            // 查询案由列表
            $list = Db::name('case_cause')
                ->where($where)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select()
                ->toArray();
            
            // 构建树形结构
            $treeList = $this->buildTree($list);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $treeList,
                'count' => count($list)
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 构建树形结构
     */
    private function buildTree($list, $parentId = 0)
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                $children = $this->buildTree($list, $item['id']);
                if (!empty($children)) {
                    $item['children'] = $children;
                }
                $tree[] = $item;
            }
        }
        return $tree;
    }
    
    /**
     * 查看案由详情
     */
    public function view()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $casecause = Db::name('case_cause')
                ->where('id', $param['id'])
                ->where('delete_time', 0)
                ->find();
            
            if (empty($casecause)) {
                return json(['code' => 404, 'msg' => '案由不存在']);
            }
            
            // 获取父级案由名称
            if ($casecause['parent_id'] > 0) {
                $parentCause = Db::name('case_cause')
                    ->where('id', $casecause['parent_id'])
                    ->where('delete_time', 0)
                    ->value('name');
                $casecause['parent_name'] = $parentCause ?: '';
            } else {
                $casecause['parent_name'] = '顶级案由';
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $casecause
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取案由选择列表（用于下拉选择）
     */
    public function select_list()
    {
        try {
            // 查询启用的案由列表
            $list = Db::name('case_cause')
                ->where('delete_time', 0)
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->select()
                ->toArray();
            
            // 构建树形结构
            $treeList = $this->buildSelectTree($list);
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $treeList
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 构建选择树形结构
     */
    private function buildSelectTree($list, $parentId = 0, $level = 0)
    {
        $tree = [];
        foreach ($list as $item) {
            if ($item['parent_id'] == $parentId) {
                // 添加缩进来表示层级关系
                $indent = str_repeat('　', $level); // 使用全角空格
                $item['name_with_indent'] = $indent . $item['name'];
                
                $tree[] = $item;
                
                $children = $this->buildSelectTree($list, $item['id'], $level + 1);
                if (!empty($children)) {
                    $tree = array_merge($tree, $children);
                }
            }
        }
        return $tree;
    }
    
    /**
     * 搜索案由（用于远程搜索）
     */
    public function search()
    {
        $keyword = Request::param('keyword', '');
        
        if (empty($keyword)) {
            return json(['code' => 0, 'msg' => 'success', 'data' => []]);
        }
        
        try {
            // 查询启用的案由列表，支持关键词搜索
            $list = Db::name('case_cause')
                ->where('delete_time', 0)
                ->where('name', 'like', '%' . trim($keyword) . '%')
                ->order('sort', 'asc')
                ->order('id', 'asc')
                ->limit(20) // 限制返回数量，避免数据量过大
                ->select()
                ->toArray();
            
            // 为每个案由添加缩进名称
            foreach ($list as &$item) {
                // 计算层级并添加缩进
                $level = $this->getCaseCauseLevel($item['id']);
                $indent = str_repeat('　', $level); // 使用全角空格
                $item['name_with_indent'] = $indent . $item['name'];
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $list
            ]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '搜索失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取案由层级
     */
    private function getCaseCauseLevel($id, $level = 0)
    {
        $caseCause = Db::name('case_cause')
            ->where('id', $id)
            ->where('delete_time', 0)
            ->find();
        
        if (!$caseCause || $caseCause['parent_id'] == 0) {
            return $level;
        }
        
        return $this->getCaseCauseLevel($caseCause['parent_id'], $level + 1);
    }
    
    /**
     * 新增案由
     */
    public function add()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '案由名称不能为空']);
        }
        
        $data = [
            'name' => $param['name'],
            'parent_id' => $param['parent_id'] ?? 0,
            'sort' => $param['sort'] ?? 0,
            'create_time' => time(),
            'update_time' => time()
        ];
        
        try {
            // 新增案由
            $casecauseId = Db::name('case_cause')->insertGetId($data);
            
            return json(['code' => 0, 'msg' => '保存成功', 'data' => ['id' => $casecauseId]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '保存失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 编辑案由
     */
    public function edit()
    {
        $param = Request::param();
        
        // 数据验证
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        if (empty($param['name'])) {
            return json(['code' => 400, 'msg' => '案由名称不能为空']);
        }
        
        // 检查案由是否存在
        $casecause = Db::name('case_cause')
            ->where('id', $param['id'])
            ->where('delete_time', 0)
            ->find();
        
        if (!$casecause) {
            return json(['code' => 404, 'msg' => '案由不存在']);
        }
        
        $data = [
            'id' => $param['id'],
            'name' => $param['name'],
            'parent_id' => $param['parent_id'] ?? $casecause['parent_id'],
            'sort' => $param['sort'] ?? $casecause['sort'],
            'update_time' => time()
        ];
        
        try {
            // 更新案由
            Db::name('case_cause')->update($data);
            
            return json(['code' => 0, 'msg' => '更新成功', 'data' => ['id' => $param['id']]]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除案由
     */
    public function delete()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            // 检查案由是否存在
            $casecause = Db::name('case_cause')
                ->where('id', $param['id'])
                ->where('delete_time', 0)
                ->find();
            
            if (!$casecause) {
                return json(['code' => 404, 'msg' => '案由不存在']);
            }
            
            // 检查是否有子级案由
            $childCount = Db::name('case_cause')
                ->where('parent_id', $param['id'])
                ->where('delete_time', 0)
                ->count();
            
            if ($childCount > 0) {
                return json(['code' => 400, 'msg' => '该案由下有子级案由，不能删除']);
            }
            
            // 检查是否有案件使用该案由
            $caseCount = Db::name('lawcase')
                ->where('case_cause_id', $param['id'])
                ->where('delete_time', 0)
                ->count();
            
            if ($caseCount > 0) {
                return json(['code' => 400, 'msg' => '有案件使用该案由，不能删除']);
            }
            
            Db::name('case_cause')
                ->where('id', $param['id'])
                ->update([
                    'delete_time' => time(),
                    'update_time' => time()
                ]);
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '删除失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新案由排序
     */
    public function sort()
    {
        $param = Request::param();
        
        if (empty($param['id'])) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        try {
            $data = [
                'id' => $param['id'],
                'sort' => $param['sort'] ?? 0,
                'update_time' => time()
            ];
            
            Db::name('case_cause')->update($data);
            
            return json(['code' => 0, 'msg' => '排序更新成功']);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => '排序更新失败: ' . $e->getMessage()]);
        }
    }
}